﻿using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using VerticalMenu.Commands;

namespace VerticalMenu
{
	public class CmdsExternalEventHandler : IExternalEventHandler
	{
		public ExternalCommandData CommandData
		{
			set
			{
				this.m_CommandData = value;
			}
		}

		public CommandInfos CurrentCmdInfos
		{
			set
			{
				this.m_CurrentCmdInfos = value;
			}
		}

		public CmdsExternalEventHandler(ExternalCommandData commandData, ElementSet elements)
		{
			this.m_CommandData = commandData;
			this.m_Elements = elements;
		}

		public void Execute(UIApplication app)
		{
			try
			{
				bool flag = this.m_CurrentCmdInfos != null;
				if (flag)
				{
					bool flag2 = ExternalCommandShowPage._hWndRevit == null;
					if (flag2)
					{
						Process currentProcess = Process.GetCurrentProcess();
						IntPtr mainWindowHandle = currentProcess.MainWindowHandle;
						ExternalCommandShowPage._hWndRevit = new WindowHandle(mainWindowHandle);
					}
					int wMsg = 7;
					CmdsExternalEventHandler.SendMessage(ExternalCommandShowPage._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
					Assembly assembly = Assembly.LoadFrom(this.m_CurrentCmdInfos.DllName);
					IExternalCommand externalCommand = assembly.CreateInstance(this.m_CurrentCmdInfos.ClassName) as IExternalCommand;
					externalCommand.Execute(this.m_CommandData, ref this.m_Message, this.m_Elements);
					this.m_CurrentCmdInfos = null;
				}
			}
			catch (Exception)
			{
				this.m_CurrentCmdInfos = null;
			}
		}

		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public string GetName()
		{
			return "CmdsExternalEventHandler";
		}

		private ExternalCommandData m_CommandData = null;

		private string m_Message = "";

		private ElementSet m_Elements = null;

		private CommandInfos m_CurrentCmdInfos = null;
	}
}
